package com.qf.controller;

import lombok.SneakyThrows;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 使用第三方jar包的方式进行文件上传操作
 * commons-io.jar/commons-fileupload.jar包
 */
@WebServlet( "/otherUpload")
public class OtherUploadFileServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //第三方jar包提供API,判断前端表单提交的数据的时候,是否是一种多文件上传(既有普通表单元素,上传组件...)
        //ServletFileUpload--->提供一个方法:boolean isMultipartContent(HttpServletRequest request)
        if(ServletFileUpload.isMultipartContent(request)){
            //是多文件上传
            //创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory() ;
            //创建上传对象
            //public ServletFileUpload(FileItemFactory fileItemFactory)
            ServletFileUpload upload = new ServletFileUpload(factory) ;

            //获取List集合存储每一个磁盘所在的文件项:FileItem
            //Servlet上传对象解析 前端发送的请求--->获取到请求的文件项
            //ublic List parseRequest(HttpServletRequest request)
            List<FileItem> list = upload.parseRequest(request);
            //遍历每一个文件项
            for(FileItem fileItem :list){
                //判断是否是普通表单元素
                //boolean isFormField()
                if(fileItem.isFormField()){
                    //是
                    //获取key以及value
                    String fieldName = fileItem.getFieldName();
                    System.out.println(fieldName) ;
                    // String getString(String var1)

                }else{
                    //文件组件
                    //String getName()  :获取文件上传的名称
                    String name = fileItem.getName();
                    System.out.println(name) ;
                    //自己创建File对象
                    File file = new File("D:\\EE_2302\\day43\\code\\Maven_2302\\src\\main\\webapp\\myImage\\"+name) ;
                    //写入
                    fileItem.write(file) ;
                }
            }

        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
